// const WS_URL = 'ws://10.202.206.173:18080/chat/ws'
const WS_URL = 'ws://192.168.56.1:18080/chat/ws'
import {useUserStore} from '@/stores/modules/user'
class WebSocket {
  // 构造函数
  constructor(options = {}) {
    this.options = options
    this.socketTask = null
    this.isOpenSocket = false //避免重复连接
    this.heartbeatInterval = options.heartbeatInterval || 10000 // 心跳间隔，默认为10秒
    this.reconnectInterval = options.reconnectInterval || 5000 // 重连间隔，默认为5秒
    this.reconnectAttempts = options.reconnectAttempts || Infinity // 最大重连次数，默认为无限次
    this.needbeat = options.needbeat || true
    this.reconnectCount = 0
    this.isNormalClosed = false
  }

  // 创建 websocket 连接
    initSocketConnect() {
        const userStore = useUserStore()
        if (!userStore.token) {
            return
        }
        
        // 根据平台构建不同的连接配置
        let connectConfig = {
          url: WS_URL,
          success: () => {
            console.log(
              '============WebSocket正在连接中...==============='
            )
            return this.socketTask
          },
          fail: (err) => {
            console.error('WebSocket连接失败', err)
            // this.reconnect()
          }
        }
        
        // #ifdef H5
        // H5环境下将token作为请求参数传递
        const urlWithToken = `${WS_URL}?authorization=${encodeURIComponent(userStore.token)}`
        connectConfig.url = urlWithToken
        console.log('H5环境WebSocket连接URL:', urlWithToken)
        // #endif
        
        // #ifndef H5
        // 非H5环境下将token放在header中
        connectConfig.header = {
          'Authorization': userStore.token
        }
        console.log('非H5环境WebSocket连接，token在header中')
        // #endif
        
        this.socketTask = uni.connectSocket(connectConfig)
    // 监听WebSocket打开事件
    this.socketTask.onOpen(() => {
      console.log(
        '==============WebSocket连接成功==================='
      )
      this.isOpenSocket = true
      // 监听接收消息
      this.socketTask.onMessage((res) => {
        // 反序列化
        const resData = JSON.parse(res.data)
          console.log('收到消息', resData)
          // 是否需要心跳
          if(this.needbeat) {
            this.resetHeartbeat()
          }
      })
    })
    // 监听WebSocket关闭事件
    this.socketTask.onClose((res) => {
      this.isOpenSocket = false
      console.log(
        '==============WebSocket连接已关闭=================',
        res
      )
      if (!this.isNormalClosed) {
        // this.reconnect()
      }
    })

    // 监听WebSocket错误事件
    this.socketTask.onError((err) => {
      console.error(
        '===============WebSocket发生错误====================',
        err
        )
        if(err.errMsg === 'createSocketTask:fail wcwss exceed max concurrent count') {
            this.reconnectCount = 0
            this.close()
        }
    //   this.reconnect()
    })
  }

  // 发送消息
  send({ type, data }) {
    return new Promise((resolve, reject) => {
      this.socketTask.send({
        // 序列化
        data: JSON.stringify({
          type,
          data
        }),
        success: () => {
          resolve()
          console.log('消息发送成功')
        },
        fail: (err) => {
          console.error(data, ' 消息发送失败', err)
          reject(err)
        }
      })
    })
  }

  // 心跳检测
  startHeartbeat() {
    this.heartbeatTimer = setInterval(() => {
      this.sendHeartbeat()
    }, this.heartbeatInterval)
  }
  // 重置心跳计时器
  resetHeartbeat() {
    clearInterval(this.heartbeatTimer)
    this.startHeartbeat()
  }
  // 发送心跳消息
    sendHeartbeat() {
      // 设置消息内容为'ping'
  }
  // 重连逻辑
  reconnect() {
    if (this.reconnectCount < this.reconnectAttempts) {
      setTimeout(() => {
        this.initSocketConnect()
        this.reconnectCount++
      }, this.reconnectInterval)
    }
  }
  // 关闭连接
  close() {
    this.isOpenSocket = false
    this.isNormalClosed = true
    if (this.socketTask) {
      this.socketTask.close({
        success: () => {
          console.log('WebSocket连接已关闭/已断开')
        },
        fail: (err) => {
          console.error('WS关闭失败->', err)
        }
      })
      clearInterval(this.heartbeatTimer)
    }
  }
}

// 默认导出实例
export default new WebSocket()
